package com.yx.changdao.web.config.quartz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yx.changdao.common.entity.NoWorkday;
import com.yx.changdao.common.entity.Problem;
import com.yx.changdao.common.enums.DifficultLevel;
import com.yx.changdao.common.utils.Dates;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.service.NoWorkdayService;
import com.yx.changdao.service.ProblemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.xml.bind.SchemaOutputResolver;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 开启定时任务,由于是简单任务,没用quartz(过于复杂) ,而是使用线程池+定时任务的方式
 *
 * @author xiapeixin
 * @date 2020-4-8
 */

@Configuration
@EnableScheduling
public class ScheduledTasks {

    public static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

    /**
     * 问题服务
     */
    @Autowired
    protected ProblemService problemService;

    /**
     * 节假日服务
     */
    @Autowired
    protected NoWorkdayService noWorkdayService;

    /**
     * 线程池使用线程池执行, 提高效率
     */
    protected ThreadPoolExecutor poolExecutor;

    /**
     * 问题处理是即将逾期, 是否已逾期,每天凌晨0点1分1秒执行
     */
    @Scheduled(cron = "1 1 0 * * ?")
    //@Scheduled(cron = "1 10 * * * ?")
    public void ifTimeoutCto() {

        poolExecutor.execute(() -> {
            //查询所有的非工作日 字符串形式
            List<String> noWorks = noWorkdayService.
                    list(new QueryWrapper<NoWorkday>().select(NoWorkday.NO_WORKDAY)).
                    stream().map(NoWorkday::getNoWorkday).collect(Collectors.toList());

            //计算即将逾期的
            logger.info("开始计算即将逾期");
            List<Problem> problems = problemService.list(new QueryWrapper<Problem>()
                    .select(Problem.ID, Problem.DEAL_LIMIT_TIME, Problem.DIFFICULT_LEVEL)
                    .eq(Problem.IF_ASSIGN, 1).in(Problem.IF_DEAL, 0,2) // 已分配并且未处理,打回处理
                    .eq(Problem.IF_DIFFICULT, 0)// 非疑难件
                    .eq(Problem.DIFFICULT_LEVEL_STATUS, 2)); //难度上报通过的

            for (Problem problem : problems) {

                Calendar cld = Calendar.getInstance(Locale.CHINA); // 时间基准,
                cld.setTime(problem.getDealLimitTime());

                //取临近逾期天数 根据难度
                Integer overdueDay = DifficultLevel.getOverdueDay(problem.getDifficultLevel());

                while (true) {
                    if (overdueDay <= 0) {
                        break;
                    }
                    cld.add(Calendar.DAY_OF_MONTH, -1);
                    //如果是非工作日 ,那么跳过
                    if (noWorks.contains(Dates.format().format(cld.getTime()))) {
                        continue;
                    }
                    overdueDay -= 1;
                }
                if (Faster.now().getTime() >= cld.getTime().getTime()) {
                    //即将逾期
                    problem.setIfTimeout(2);
                    problemService.updateById(problem);
                }
            }
            logger.info("结束计算即将逾期");
        });
    }

    /**
     * 已经逾期  0点1分5秒执行
     */
    @Scheduled(cron = "5 1 0 * * ?")
    public void ifTimeoutAl() {
        poolExecutor.execute(() -> {
            //计算已逾期的
            logger.info("开始计算即已逾期");
            problemService.update(new UpdateWrapper<Problem>()
                    .set(Problem.IF_TIMEOUT, 1) //已经逾期
                    .eq(Problem.IF_ASSIGN, 1).in(Problem.IF_DEAL, 0,2) // 已分配并且未处理,打回处理
                    .eq(Problem.IF_DIFFICULT, 0)// 非疑难件
                    .eq(Problem.DIFFICULT_LEVEL_STATUS, 2) //难度上报通过的
                    .le(Problem.DEAL_LIMIT_TIME, Faster.now())); //已超出时间
            logger.info("结束计算即已逾期");
        });
    }


    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        this.poolExecutor = new ThreadPoolExecutor(16, 16,
                5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(128));
    }


}

